<template>
  <div class="dashboard-container">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="nav-left">
        <div class="nav-dropdown">
          <el-select
            v-model="workShop"
            style="width: 120px"
            clearable
            placeholder="请选择车间"
            @change="changeWorkShop"
          >
            <el-option
              v-for="item in workShopOpts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

          <div class="filter-dropdown">
            <el-select
              v-model="lines"
              style="width: 150px"
              clearable
              multiple
              collapse-tags
              placeholder="请选择产线"
              @change="changeLines"
            >
              <el-option
                v-for="item in productionLineOpts"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="filter-dropdown">
            <el-date-picker
              v-model="selectTime"
              type="daterange"
              style="width: 230px"
              value-format="yyyy-MM-dd"
              @change="changeSelectTime"
            >
            </el-date-picker>
          </div>
        </div>
      </div>
      <div class="title">车间智能可视化大屏</div>
      <div class="nav-right">
        <div class="flBtn" @click="fluch">刷新</div>
        <span class="date">{{ currentDate }}</span>
        <span class="time">{{ currentTime }}</span>
        <div v-if="!showType">
          <img
            style="width: 24px; height: 24px; cursor: pointer"
            @click="fullScreen"
            src="../images/sf.png"
            alt=""
          />
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 左侧内容栏 -->
      <div class="left-content">
        <!-- 计划达成率 -->
        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">计划达成率</div>
            </div>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '280px' }"
            id="defect-rate-chart"
          ></div>
        </div>

        <!-- 日报废率-->
        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">日报废率</div>
            </div>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '280px' }"
            id="rbfl-chart"
          ></div>
        </div>
      </div>

      <!-- 右侧内容栏 -->
      <div class="right-content">
        <!-- 工时趋势图 -->
        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">工时趋势图</div>
            </div>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '280px' }"
            id="capacity-chart"
          ></div>
        </div>

        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">FQC批合格率</div>
            </div>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '280px' }"
            id="fqc-chart"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  planAchievementRate,
  calculateScrappedRate,
  fqcBatchPassRate,
  workingHoursTrend,
  realProductionTrend,
} from "@/api/productionLineLargeScreen.js";

import { workshop, lineList } from "@/api/common.js";

export default {
  name: "ProductionDashboard",
  data() {
    return {
      currentDate: "",
      currentTime: "",
      productionData: [],
      productionLine: "",
      productionLineOpts: [],
      workShop: "",
      workShopOpts: [],
      lines: [],
      selectTime: [
        new Date().toISOString().split("T")[0],
        new Date().toISOString().split("T")[0],
      ],
      defectRateChart: null,
      colorList: [
        "#4dabf7",
        "#38d9a9",
        "#ffe066",
        // "#F2F2F2",
        "#00FFFF",
        "#95F20",
        "#FFFF00",
        "F59A23",
        "D9001B",
        "8400FF",
      ],
    };
  },
  props: ["showType"],
  created() {
    const start = new Date();
    start.setMonth(start.getMonth() - 1);
    this.selectTime = [
      start.toISOString().split("T")[0],
      new Date().toISOString().split("T")[0],
    ];
  },
  mounted() {
    this.initTime();
    this.fetchDefectRateData();
    this.getWorkshop();
  },
  methods: {
    fluch() {
      this.fetchProductionData(); //达成率
      this.fetchFQCData(); //fqc
      this.fetchRbflData(); //日报废率
      this.fetchCapacityData(); //工时
    },
    changeLines(val) {
      this.lines = val;
      this.fetchProductionData();
      this.fetchFQCData(); //fqc
      this.fetchRbflData(); //日报废率
      this.fetchCapacityData(); //工时
    },
    changeSelectTime(val) {
      this.selectTime = val;
      this.fetchProductionData();
      this.fetchFQCData(); //fqc
      this.fetchRbflData(); //日报废率
      this.fetchCapacityData(); //工时
    },
    fullScreen() {
      window.open("/#/O3-workorder");
    },
    changeWorkShop(val) {
      this.workShop = val;
      this.getlineList();
      // this.fetchProductionData(); //达成率
      // this.fetchFQCData(); //fqc
      // this.fetchRbflData(); //日报废率
      // this.fetchCapacityData(); //工时
    },
    async getWorkshop() {
      const res = await workshop();
      if (res) {
        this.workShopOpts = res.data.data.records.map((item) => {
          return {
            value: item.id,
            label: item.workshopName,
          };
        });
        this.workShop = this.workShopOpts[0].value;

        this.getlineList();
      }
    },

    async getlineList() {
      let data = {
        workshopId: this.workShop,
        current: 1,
        size: 999,
      };
      const res = await lineList(data);
      this.productionLineOpts = res.data.data.records.map((item) => {
        return {
          value: item.id,
          label: item.realityLineName,
        };
      });

      this.lines = [this.productionLineOpts[0].value];

      this.fetchProductionData(); //达成率
      this.fetchFQCData(); //fqc
      this.fetchRbflData(); //日报废率
      this.fetchCapacityData(); //工时
    },
    initTime() {
      // 初始化时间
      const now = new Date();
      this.currentDate = this.formatDate(now);
      this.currentTime = this.formatTime(now);

      // 每秒更新时间
      setInterval(() => {
        this.currentTime = this.formatTime(new Date());
      }, 1000);
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");
      return `${hours}:${minutes}:${seconds}`;
    },

    getStatusText(status) {
      const statusMap = {
        normal: "正常",
        warning: "警告",
        error: "异常",
      };
      return statusMap[status] || status;
    },

    fetchProductionData() {
      let data = {
        workshop: this.workShop,
        lines: this.lines,
        startDate: this.selectTime[0],
        endDate: this.selectTime[1],
      };

      if (this.lines.length == 0) {
        return;
      }

      planAchievementRate(data)
        .then((response) => {
          this.defectRateChart = response.data;

          let series = this.lines.map((item, index) => {
            return [
              {
                name: this.productionLineOpts.find((its) => its.value == item)
                  .label,
                type: "bar",
                yAxisIndex: 0,
                data: response.data.data[item + "_bar"],
                itemStyle: {
                  color: this.colorList[index],
                },
              },
              {
                name: this.productionLineOpts.find((its) => its.value == item)
                  .label,
                type: "line",
                yAxisIndex: 1,
                data: response.data.data[item + "_clo"],
                symbol: "circle",
                symbolSize: 8,
                lineStyle: {
                  color: this.colorList[index],
                },
                itemStyle: {
                  color: this.colorList[index],
                },
              },
            ];
          });

          const defectRateChart = echarts.init(
            document.getElementById("defect-rate-chart")
          );
          defectRateChart.setOption(
            {
              grid: {
                left: "4%",
                right: "4%",
                bottom: "3%",
                top: "12%",
                containLabel: true,
              },

              tooltip: {
                trigger: "axis",
                formatter: function (params) {
                  let tooltipContent = "";
                  var xAxisValue = params[0].name;
                  tooltipContent =
                    "<div style='margin-bottom:6px'>" + xAxisValue + "</div>";
                  params.forEach(function (item) {
                    let unit = ""; // 默认无单位
                    var colorDot =
                      '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:' +
                      item.color +
                      ';"></span>';
                    if (item.seriesType === "bar") unit = " ";
                    else if (item.seriesType === "line") unit = "%";
                    tooltipContent +=
                      colorDot +
                      item.seriesName +
                      ":" +
                      `  <div style="display:inline-block;margin:0 5px;font-weight:600">${
                        item.value ? item.value : 0
                      }</div>` +
                      unit +
                      "<br/>";
                  });
                  return tooltipContent;
                },
              },
              xAxis: {
                type: "category",
                data: response.data.data.xAxis,
              },
              yAxis: [
                {
                  type: "value",
                  name: "产能",
                  position: "left",
                  max: 3000,
                  min: 0,
                  splitLine: {
                    show: true,
                    lineStyle: {
                      type: "dashed", //y轴分割线类型
                      color: "#cccccc",
                      width: 1,
                    },
                  },
                },
                {
                  type: "value",
                  name: "计划完成率",
                  position: "right",
                  axisLabel: {
                    color: "#333",
                    formatter: "{value} %",
                  },
                  max: 150,
                  min: 0,
                  splitLine: {
                    show: true,
                    lineStyle: {
                      type: "dashed", //y轴分割线类型
                      color: "#cccccc",
                      width: 1,
                    },
                  },
                },
              ],
              series: series.flat(Infinity),
            },
            true
          );

          this.productionData = response.data;
        })
        .catch((error) => {
          console.error("获取生产进度数据失败:", error);
        });

      // 窗口大小改变时，重新调整图表大小
      window.addEventListener("resize", () => {
        defectRateChart.resize();
      });
    },
    // 预留接口：获取不良率数据
    fetchDefectRateData() {
      console.log("获取不良率数据接口已调用");
    },

    fetchRbflData() {
      let data = {
        workshop: this.workShop,
        lines: this.lines,
        startDate: this.selectTime[0],
        endDate: this.selectTime[1],
      };

      calculateScrappedRate(data)
        .then((response) => {
          let series = this.lines.map((item, index) => {
            return {
              name: this.productionLineOpts.find((its) => its.value == item)
                .label,
              data: response.data.data[item],
              type: "line",
              symbol: "circle",
              symbolSize: 8,
              lineStyle: {
                width: 2,
                color: this.colorList[index],
              },
              itemStyle: {
                color: this.colorList[index],
              },
            };
          });
          const rbflChart = echarts.init(document.getElementById("rbfl-chart"));
          rbflChart.setOption(
            {
              grid: {
                left: "4%",
                right: "4%",
                bottom: "3%",
                top: "12%",
                containLabel: true,
              },
              xAxis: {
                type: "category",
                data: response.data.data.xAxis,
              },
              tooltip: {
                trigger: "axis",
                formatter: function (params) {
                  // params 是一个数组，包含了每个系列的数据
                  let tooltipContent = "";
                  var xAxisValue = params[0].name;
                  tooltipContent =
                    "<div style='margin-bottom:6px'>" + xAxisValue + "</div>";
                  params.forEach(function (item) {
                    // 拼接 tooltip 内容，这里简单地在数值后面加上了 %
                    var colorDot =
                      '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:' +
                      item.color +
                      ';"></span>';
                    tooltipContent +=
                      colorDot +
                      item.seriesName +
                      ":" +
                      `  <div style="display:inline-block;margin:0 5px;font-weight:600">${
                        item.value ? item.value : 0
                      }</div>` +
                      "%<br/>";
                  });
                  return tooltipContent;
                },
              },
              yAxis: {
                type: "value",
                name: "报废率",
                position: "right",
                axisLabel: {
                  color: "#333",
                  formatter: "{value} %",
                },
                splitLine: {
                  show: true,
                  lineStyle: {
                    type: "dashed", //y轴分割线类型
                    color: "#ccc",
                    width: 1,
                  },
                },
              },
              series: series,
            },
            true
          );

          window.addEventListener("resize", () => {
            rbflChart.resize();
          });
        })
        .catch((error) => {
          console.error("获取 FQC 数据失败:", error);
        });
    },
    // 预留接口：获取 FQC 数据
    async fetchFQCData() {
      console.log("获取 FQC 数据接口已调用");
      let data = {
        workshops: [this.workShop],
        lines: this.lines,
        startDate: this.selectTime[0],
        endDate: this.selectTime[1],
      };
      console.log(data);

      const res = await fqcBatchPassRate(data);

      let series = this.lines.map((item, index) => {
        return [
          {
            name: this.productionLineOpts.find((its) => its.value == item)
              .label,
            type: "line",
            yAxisIndex: 0,
            data: res.data.data[item + "_line"].map((item) =>
              item ? (item * 100).toFixed(1) : ""
            ),
            symbol: "circle",
            symbolSize: 8,
            lineStyle: {
              width: 2,
              color: this.colorList[index],
            },
            itemStyle: {
              color: this.colorList[index],
            },
          },
        ];
      });

      const fqcChart = echarts.init(document.getElementById("fqc-chart"));
      fqcChart.setOption(
        {
          grid: {
            left: "4%",
            right: "4%",
            bottom: "3%",
            top: "12%",
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              // params 是一个数组，包含了每个系列的数据
              let tooltipContent = "";
              var xAxisValue = params[0].name;
              tooltipContent =
                "<div style='margin-bottom:6px'>" + xAxisValue + "</div>";
              params.forEach(function (item) {
                // 拼接 tooltip 内容，这里简单地在数值后面加上了 %
                var colorDot =
                  '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:' +
                  item.color +
                  ';"></span>';
                tooltipContent +=
                  colorDot +
                  item.seriesName +
                  ":" +
                  `  <div style="display:inline-block;margin:0 5px;font-weight:600">${
                    item.value ? item.value : 0
                  }</div>` +
                  "%<br/>";
              });
              return tooltipContent;
            },
          },
          xAxis: {
            type: "category",
            data: res.data.data.xAxis,
          },
          yAxis: [
            {
              type: "value",
              name: "合格率",
              position: "right",
              axisLabel: {
                color: "#333",
                formatter: "{value} %",
              },
              max: 100,
              min: 0,
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", //y轴分割线类型
                  color: "#ccc",
                  width: 1,
                },
              },
            },
          ],
          series: series.flat(Infinity),
        },
        true
      );

      window.addEventListener("resize", () => {
        fqcChart.resize();
      });
    },
    // 预留接口：工时趋势数据
    async fetchCapacityData() {
      let lineNames = this.lines.map((item) => {
        return this.productionLineOpts.find((i) => {
          return i.value == item;
        }).label;
      });

      let workshopNames = this.workShopOpts.find(
        (item) => item.value == this.workShop
      ).label;

      let data = {
        workshops: [this.workShop],
        lines: this.lines,
        startDate: this.selectTime[0],
        endDate: this.selectTime[1],
        workshopNames: [workshopNames],
        lineNames,
      };

      console.log(data);

      const res = await workingHoursTrend(data);

      let series = this.lines.map((item, index) => {
        return {
          name: this.productionLineOpts.find((its) => its.value == item).label,
          data: res.data.data[item + "_line"],
          type: "line",
          symbol: "circle",
          symbolSize: 8,
          lineStyle: {
            width: 2,
            color: this.colorList[index],
          },
          itemStyle: {
            color: this.colorList[index],
          },
        };
      });

      // 初始化产能趋势图
      const capacityChart = echarts.init(
        document.getElementById("capacity-chart")
      );
      capacityChart.setOption(
        {
          grid: {
            left: "4%",
            right: "4%",
            bottom: "3%",
            top: "12%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            data: res.data.data.xAxis,
          },
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              // params 是一个数组，包含了每个系列的数据
              let tooltipContent = "";
              var xAxisValue = params[0].name;
              tooltipContent =
                "<div style='margin-bottom:6px'>" + xAxisValue + "</div>";
              params.forEach(function (item) {
                // 拼接 tooltip 内容，这里简单地在数值后面加上了 %
                var colorDot =
                  '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:' +
                  item.color +
                  ';"></span>';
                tooltipContent +=
                  colorDot +
                  item.seriesName +
                  ":" +
                  `  <div style="display:inline-block;margin:0 5px;font-weight:600">${
                    item.value ? item.value : 0
                  }</div>` +
                  "h<br/>";
              });
              return tooltipContent;
            },
          },
          yAxis: {
            name: "工时",
            type: "value",
            position: "right",
            axisLabel: {
              color: "#333",
              formatter: "{value} h",
            },
            max: 3,
            min: 0,
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed", //y轴分割线类型
                color: "#cccccc",
                width: 1,
              },
            },
          },
          series: series,
        },
        true
      );

      window.addEventListener("resize", () => {
        capacityChart.resize();
      });
    },
  },
};
</script>

<style scoped>
.dashboard-container {
  height: 100%;
  font-family: "Arial", sans-serif;
  background-color: #e2eef7;
  color: #fff;
  padding: 0 10px;
  box-sizing: border-box;
}

.flBtn {
  border: 1px solid #1e88e5;
  color: #1e88e5;
  padding: 4px 20px;
  margin-left: 20px;
  border-radius: 5px;
  cursor: pointer;
}

.header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  background: #fff;
  margin-bottom: 10px;
}

.nav-left {
  display: flex;
  align-items: center;
}

.home-icon {
  margin-right: 15px;
  font-size: 20px;
}

.nav-dropdown {
  display: flex;
  align-items: center;
  position: relative;
  margin-right: 10px;
  cursor: pointer;
}

.dropdown-icon {
  margin-left: 5px;
  font-size: 12px;
}

.title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.nav-right {
  display: flex;

  align-items: center;
}

.date,
.time {
  font-size: 16px;
  font-weight: 600;
  margin: 3px 10px;
  color: #555;
}

.content {
  display: flex;
  /* height: calc(100vh - 60px); */
  height: 92%;
  gap: 10px;
}

.left-content,
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.panel {
  background: #fff;
  border: 1px solid #63b1d3;
  border-radius: 5px;
  padding: 10px;
}
.hander {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.panel-title {
  font-size: 14px;
  font-weight: bold;
  color: #555555;
}

.view-report {
  background-color: transparent;
  border: 1px solid #1e88e5;
  color: #1e88e5;
  padding: 3px 8px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  margin-left: 20px;
}

.panel-filters {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.filter-dropdown {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: rgba(255, 255, 255, 0.1);

  border-radius: 3px;
  color: #fff;
  cursor: pointer;
}

.filter-icon {
  margin-left: 5px;
  font-size: 12px;
}

.panel-chart {
  height: 420px;
  width: 100%;
}

.progress-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 8px 10px;
  text-align: center;
  border: 1px solid #63b1d3;
}

th {
  background-color: rgba(26, 59, 127, 0.5);
}

.status-normal {
  color: #4caf50;
}

.status-warning {
  color: #ff9800;
}

.status-error {
  color: #f44336;
}
</style>
